# -*- coding: utf-8 -*-
import re
from PyQt5.QtWidgets import QWidget, QLineEdit, QPushButton, QHBoxLayout, QTableView, QVBoxLayout, QTreeView, QMessageBox, QTextEdit, QLabel
from PyQt5.QtCore import pyqtSignal, pyqtSlot
from datamodel import DataModel
from highlighter import SqlHighLighter


class QueryForm(QWidget):

    executeCompleted = pyqtSignal(str)

    def __init__(self, connection, parent=None):
        super(QueryForm, self).__init__(parent)

        self.connection = connection

        self.sqlText = QTextEdit()
        self.highlighter = SqlHighLighter(self.sqlText.document())

        queryLayout = QVBoxLayout()
        queryLayout.addWidget(self.sqlText)

        self.grid = QTableView()
        self.grid.setVisible(False)
        self.message = QLabel()

        resultLayout = QVBoxLayout()
        resultLayout.addLayout(queryLayout)
        resultLayout.addWidget(self.grid)
        resultLayout.addWidget(self.message)

        viewLayout = QHBoxLayout()
        viewLayout.addLayout(resultLayout)

        mainLayout = QHBoxLayout()
        mainLayout.addLayout(viewLayout)
        self.setLayout(mainLayout)
        self.setOpened(True)

    @pyqtSlot(bool)
    def setOpened(self, enabled):
        self.sqlText.setEnabled(enabled)
        self.grid.setEnabled(enabled)
        self.setEnabled(enabled)
        if not enabled:
            return
        
    def _getTableList(self):
        sql = "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name"
        cursor = self.connection.execute(sql)
        table = []
        for row in cursor.fetchall():
            table.append(row)
        cursor.close()
        return table

    def execute(self):
        tc = self.sqlText.textCursor()
        sql = tc.selectedText()
        if sql == '':
            sql = self.sqlText.toPlainText()

        if sql == "":
            return

        sub = re.compile(r'\s+')
        sql = sub.sub(r' ', sql)

        print(u'%s' % sql.encode('utf8'))

        if self.connection is None:
            QMessageBox.information(self, "No database", "Open or create a database")
            return

        msg = ""
        try:
            cursor = self.connection.cursor()
            cursor.execute(sql)
            if cursor.description is not None: # data query
                # Binding data grid
                self.grid.setModel(DataModel(cursor.fetchall(), cursor.description))
                self.grid.setVisible(True)
                self.message.setVisible(False)
            else:
                self.grid.setModel(DataModel(None, None))
                self.grid.setVisible(False)
                self.message.setVisible(True)
            msg = "执行SQL成功"
            cursor.close()
            self.connection.commit()
        except Exception as ex:
            print(ex)
            msg = '%s' % ex
            self.grid.setVisible(False)
            self.message.setVisible(True)
        print(msg)
        self.message.setText(msg)
        self.executeCompleted.emit(msg)
